package cn.itcast.controller;

import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.Result;
import cn.itcast.pojo.OrderSetting;
import cn.itcast.service.OrderSettingService;
import cn.itcast.utils.POIUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/ordersetting")
@CrossOrigin
public class OrderSettingController {

    @Reference
    private OrderSettingService orderSettingService;

    @PostMapping("/upload")
    public Result importOrderSetting(@RequestParam("excelFile") MultipartFile file) {
        try {
            List<String[]> readExcel = POIUtils.readExcel(file);
            ArrayList<OrderSetting> orderSettings = new ArrayList<>();
            for (String[] strings : readExcel) {
                OrderSetting orderSetting = new OrderSetting();
                orderSetting.setOrderDate(new Date(strings[0]));
                orderSetting.setNumber(Integer.valueOf(strings[1]));
                orderSettings.add(orderSetting);
            }
            orderSettingService.importOrderSetting(orderSettings);
            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }

    }

    @GetMapping("/getOrderSettingsByMonth")
    public Result getOrderOrderSettingsByMonth(String date) {
        try {
            List<Map> list = orderSettingService.getOrderOrderSettingsByMonth(date);
            return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }

    @PutMapping("/updateOrderSettingNumber")
    public Result updateOrderSettingNumber(@RequestBody OrderSetting orderSetting) {
        try {
            orderSettingService.updateOrderSettingNumber(orderSetting);
            return new Result(true,MessageConstant.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ORDERSETTING_FAIL);
        }
    }

}
